<script setup>
//element Plus ui引入语言包
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import en from "element-plus/dist/locale/en.mjs";
//引入仓库
import useConfigStore from "@/stores/config.js";

//element Plus ui组件国际化
import { computed, onMounted, watch, toRef } from "vue";

//这里是关于验证登录的代码
import useUserStore from "@/stores/user.js";
import { checkLoginApi } from "@/api/auth.js";

import { useRouter } from "vue-router";
const router = useRouter();

const userStore = useUserStore();

//把布尔值转为可监听的对象
const isLogin = toRef(userStore, "isLogin");

onMounted(async () => {
  if (isLogin.value) {
    //检查登录是否有效
    const { error, data } = await checkLoginApi();
    if (error) {
      //检查登录失败,跳转到登录页面
      router.replace("/login");
      //清除token
      localStorage.removeItem("token");
    }
    console.log(data);
  }
});

//上面如果变为假，就会执行下面这段代码。监听登录状态变为false
watch(isLogin, () => {
  //由true变为false
  if (!isLogin.value) {
    //检查登录失败，跳转到登录页面
    router.replace("/login");
    //清除token
    localStorage.removeItem("token");
  }
});

const configStore = useConfigStore();

//element Plus切换语言
const locale = computed(() => {
  if (configStore.language === "zh") {
    return zhCn;
  } else {
    return en;
  }
});
</script>

<template>
  <keep-alive>
    <el-config-provider :locale="locale">
      <router-view></router-view>
    </el-config-provider>
  </keep-alive>
</template>

<style scoped></style>
